package com.loe.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

public class TitleView extends FrameLayout
{
    public TitleView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, context.obtainStyledAttributes(attrs, R.styleable.TitleView));
    }

    public TitleView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init(context, context.obtainStyledAttributes(attrs, R.styleable.TitleView, defStyleAttr, 0));
    }

    @SuppressLint("NewApi")
    public TitleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
    {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, context.obtainStyledAttributes(attrs, R.styleable.TitleView, defStyleAttr, defStyleRes));
    }

    private ImageView imageLeft;
    private TextView textTitle;
    private TextView textRight;

    private ImageView imageRight;

    private int statusSize;
    private boolean statusFull;
    private boolean statusTextLight;

    private FrameLayout bar;

    private void init(final Context context, TypedArray typedArray)
    {
        bar = (FrameLayout) inflate(context, R.layout.loe_title_layout, null);
        addView(bar);
        imageLeft = (ImageView) bar.findViewById(R.id.imageLeft);
        textTitle = (TextView) bar.findViewById(R.id.textTitle);
        textRight = (TextView) bar.findViewById(R.id.textRight);
        imageRight = (ImageView) bar.findViewById(R.id.imageRight);

        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        statusSize = getResources().getDimensionPixelSize(resourceId);

        setBackListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                try
                {
                    ((Activity) context).onBackPressed();
                } catch (Exception e)
                {
                }
            }
        });

        setLeftVisible(typedArray.getBoolean(R.styleable.TitleView_title_left_visible, true));
        setLeftImageDrawable(typedArray.getDrawable(R.styleable.TitleView_title_left_image));
        setBarHeight((int) typedArray.getDimension(R.styleable.TitleView_title_bar_height, px(48)));
        setBarVisible(typedArray.getBoolean(R.styleable.TitleView_title_bar_visible, true));
        setBarBackgroundDrawable(typedArray.getDrawable(R.styleable.TitleView_title_bar_background));
        setTitle(typedArray.getString(R.styleable.TitleView_title_text));
        setTitleBold(typedArray.getBoolean(R.styleable.TitleView_title_bold, true));
        setTitleSize(typedArray.getDimension(R.styleable.TitleView_title_size, 0));
        setTitleGravity(typedArray.getInt(R.styleable.TitleView_title_gravity, Gravity.CENTER));
        setRight(typedArray.getString(R.styleable.TitleView_title_right_text));
        setRightWidth(typedArray.getDimension(R.styleable.TitleView_title_right_width, px(49)));
        setRightImageDrawable(typedArray.getDrawable(R.styleable.TitleView_title_right_image));

        // color
        int color = typedArray.getColor(R.styleable.TitleView_title_color, -22);
        if (color != -22)
        {
            setColor(color);
        }

        // padding转移
        bar.setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom());

        // 设置status
        setStatus(typedArray.getBoolean(R.styleable.TitleView_title_status_textLight, false), typedArray.getBoolean(R.styleable.TitleView_title_status_full, false));
    }

    public void setColor(int color)
    {
        imageLeft.setColorFilter(color);
        textTitle.setTextColor(color);
        textRight.setTextColor(color);
        imageRight.setColorFilter(color);
    }

    /**
     * 设置标题栏高度
     */
    public void setBarHeight(int height)
    {
        LayoutParams params = (LayoutParams) bar.getLayoutParams();
        params.height = height;
        bar.setLayoutParams(params);
    }

    /**
     * 设置标题栏显示
     */
    public void setBarVisible(boolean visible)
    {
        bar.setVisibility(visible ? VISIBLE : GONE);
    }

    /**
     * 设置bar背景
     */
    public void setBarBackground(int resId)
    {
        bar.setBackgroundResource(resId);
    }

    /**
     * 设置bar背景
     */
    public void setBarBackgroundDrawable(Drawable drawable)
    {
        if (drawable != null)
        {
            bar.setBackground(drawable);
        }
    }

    /**
     * 设置返回图片
     */
    public void setLeftImage(int resId)
    {
        imageLeft.setImageResource(resId);
    }

    /**
     * 设置返回图片
     */
    public void setLeftImageDrawable(Drawable drawable)
    {
        if (drawable != null)
        {
            imageLeft.setImageDrawable(drawable);
        }
    }

    /**
     * 设置返回可见
     */
    public void setLeftVisible(boolean visible)
    {
        imageLeft.setVisibility(visible ? VISIBLE : GONE);
    }

    /**
     * 设置返回监听
     */
    public void setBackListener(OnClickListener listener)
    {
        imageLeft.setOnClickListener(listener);
    }

    /**
     * 设置标题文字
     */
    public void setTitle(String title)
    {
        textTitle.setText(title);
    }

    /**
     * 设置标题文字粗体
     */
    public void setTitleBold(Boolean isBold)
    {
        textTitle.setTypeface(isBold ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
    }

    /**
     * 设置标题文字大小
     */
    public void setTitleSize(float size)
    {
        size = dp(size);

        if (size < 4)
        {
            size = 16;
        }

        textTitle.setTextSize(size);
    }


    /**
     * 设置标题对齐方式
     */
    public void setTitleGravity(int gravity)
    {
        textTitle.setGravity(gravity);
    }

    /**
     * 设置右边文字
     */
    public void setRight(String right)
    {
        textRight.setText(right);
        if (right != null && !right.isEmpty())
        {
            textRight.setVisibility(VISIBLE);
            if (imageRight != null)
            {
                imageRight.setVisibility(GONE);
            }
        }else
        {
            textRight.setVisibility(GONE);
        }
    }

    /**
     * 设置右边图片
     */
    public void setRightImage(int resId)
    {
        imageRight.setImageResource(resId);
        textRight.setVisibility(GONE);
        imageRight.setVisibility(VISIBLE);
    }

    /**
     * 设置右边图片
     */
    public void setRightImageDrawable(Drawable drawable)
    {
        if (drawable != null)
        {
            imageRight.setImageDrawable(drawable);
            textRight.setVisibility(GONE);
            imageRight.setVisibility(VISIBLE);
        }
    }

    /**
     * 设置右边图片大小
     */
    public void setRightWidth(float width)
    {
        LayoutParams params = (LayoutParams) imageRight.getLayoutParams();
        params.width = (int) width;
        imageRight.setLayoutParams(params);
    }

    private long rightDelay = 0L;

    /**
     * 设置右边允许
     */
    public void setRightEnable(boolean enable)
    {
        textRight.setEnabled(enable);
        textRight.setAlpha(enable ? 1f : 0.65f);
    }

    /**
     * 设置右边图片允许
     */
    public void setRightImageEnable(boolean enable)
    {
        imageRight.setEnabled(enable);
        imageRight.setAlpha(enable ? 1f : 0.65f);
    }

    /**
     * 设置右边监听
     */
    public void setRightListener(final OnClickListener listener)
    {
        OnClickListener rightListener = new OnClickListener()
        {
            @Override
            public void onClick(final View view)
            {
                if (System.currentTimeMillis() - rightDelay > 1200)
                {
                    listener.onClick(view);
                    rightDelay = System.currentTimeMillis();
                }
            }
        };
        textRight.setOnClickListener(rightListener);
        imageRight.setOnClickListener(rightListener);
    }

    public int getStatusSize()
    {
        return statusSize;
    }

    public void setStatus(boolean isStatusTextLight, boolean isStatusFull)
    {
        statusTextLight = isStatusTextLight;
        statusFull = isStatusFull;
        upStatusBar();
    }

    /**
     * 更新状态栏
     */
    public void upStatusBar()
    {
        try
        {
            if (statusFull)
            {
                setPadding(0, statusSize, 0, 0);
                Window window = ((Activity) getContext()).getWindow();
                if (statusTextLight)
                {
                    window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                }
                else
                {
                    window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                }
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                {
                    window.setStatusBarColor(Color.TRANSPARENT);
                }
            }
            else
            {
                setPadding(0, 0, 0, 0);
                Window window = ((Activity) getContext()).getWindow();
                if (statusTextLight)
                {
                    window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                }
                else
                {
                    window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                }
            }
        } catch (Exception e)
        {
        }
    }

    public TextView getTextTitle()
    {
        return textTitle;
    }

    public FrameLayout getBar()
    {
        return bar;
    }

    public ImageView getImageLeft()
    {
        return imageLeft;
    }

    public ImageView getImageRight()
    {
        return imageRight;
    }

    private int px(float dp)
    {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density + 0.5);
    }

    public int dp(float px)
    {
        return (int) (px / Resources.getSystem().getDisplayMetrics().density + 0.5f);
    }
}